<?php 
/*****************
* 任务管理
*创建日期:2012-8-20
*作者：tjx
******************/
define('IN_WONDERSHARE', true);
header("Content-type:text/html;charset=utf-8");
ob_start("ob_gzhandler");

require('../includes/init.php');
require ('./configs/site_config.php');

class TaskManage {
	
	private  $db;
	private  $table;
	private $type;//操作类型
	/**
	* @ 构造函数
	* @ __construct
	*/
	
	public function __construct() {
		
		$this->db = $GLOBALS['db'];
		$this->table = 'task_manage';
		$type_array = array('self', 'admin', 'test', 'pub');//任务类型
		
		$this->type = trim($_REQUEST['type']);
		if ( !in_array($this->type, $type_array) ) {
			echo "任务类型错误。";
			exit;
		}
		
	}

	/**
	* 查看站点列表
	* @param   string      		 $q_user_name      用户名称
	* @return  array
	*/
	public function index() {
		
		$site_rows = array();
		$page = 1;
		if ( !empty($_REQUEST['page']) ) {
			$page = (int)$_REQUEST['page'];
		}
		$pagesize = 10;
		
		//封装搜索
		$mCreatAid = $this->type != 'self' ? (int) ($_GET['mCreatAid']) : $_SESSION['AID'];
		$mTestAid = $this->type != 'test' ? (int) ($_GET['mTestAid']) :  $_SESSION['AID'];
		$mPubAid = $this->type != 'pub' ? (int) ($_GET['mPubAid']) :  $_SESSION['AID'];
		
		$search_array = array(	'mId' => (int) $_GET['mId'],
			 					'mName' => empty($_GET['url_page']) ? trim($_GET['mName']) : urldecode($_GET['mName']),
								'sId' => (int) $_GET['sId'],
								'mCreatAid' => $mCreatAid,
								'mTestAid' => $mTestAid,
								'mPubAid' => $mPubAid,
								'type' => $this->type,
							);			
		$search_p = $this->getSearchParameters($search_array);
		
		//获取数据
		$sql = "SELECT COUNT(1) AS total 
				FROM {$this->table} m, task_site s 
				WHERE m.sId = s.sId {$search_p['where_str']} AND m.mIsDelete = 0 ";
		$page_info = get_page_info($sql, $pagesize, $page);
		$page_url = get_page_url($page, $page_info['page_num'], $search_p['url_str']);
		
		$sql = "SELECT 
				m.mId,
				m.mName,
				(SELECT AName FROM Admin WHERE AID = m.mCreatAid ) mCreatUser ,
				(SELECT AName FROM Admin WHERE AID = m.mTestAid) mTestUser ,
				(SELECT AName FROM Admin WHERE AID = m.mPubAid) mPubUser ,
				m.mEditFile,
				m.mDeleteFile,
				m.mCdnEditFile,
				m.mCdnDeleteFile,
				m.mMsgFile,
				m.mCdnMsgFile,
				m.mState,
				s.sDomainName
				FROM {$this->table} m, task_site s 
				WHERE m.sId = s.sId {$search_p['where_str']} AND m.mIsDelete = 0 
				ORDER BY m.mId DESC 
				LIMIT {$page_info['start']}, {$pagesize}";
		$manage_rows = $this->db->getAll($sql);
		
		$user_option = $this->getUserOptionInfo($search_array);//获取测试人，创建人，发布人下拉框
		$site_option = getSiteInfo($search_array['sId'], true );//站点下拉框
		//抛向页面处理
		$GLOBALS['smarty']->assign('page_url', $page_url);
		$GLOBALS['smarty']->assign('manage_rows', $manage_rows);
		$GLOBALS['smarty']->assign('user_option', $user_option);
		$GLOBALS['smarty']->assign('site_option', $site_option);
		$GLOBALS['smarty']->assign('search_array', $search_array);
		$GLOBALS['smarty']->assign('total', $page_info['total']);
		$GLOBALS['smarty']->display('task_manage_list.htm');  

		
	}
	
	/**
	* 修改或增加站点
	* @param   string      		 $q_user_name      用户名称
	* @return  array
	*/
	public function editData() {
		
		$manage_rows = array();
		$mId = (int) $_GET['mId'];

		if ( !empty($mId) ) {// 编辑
	
			$where_str = $this->type == 'self' ?  " AND m.mCreatAid = {$_SESSION['AID']} " : '';
			if ( $this->type == 'pub' ) {
				$where_str = " AND m.mPubAid = {$_SESSION['AID']} ";
			} elseif ( $this->type == 'test' ) {
				$where_str = " AND m.mTestAid = {$_SESSION['AID']} ";
				
			}
			
			$sql = "SELECT 
					m.mId,
					m.sId,
					m.mName,
					(SELECT AName FROM Admin WHERE AID = m.mCreatAid ) mCreatUser ,
					(SELECT AName FROM Admin WHERE AID = m.mTestAid) mTestUser ,
					(SELECT AName FROM Admin WHERE AID = m.mPubAid) mPubUser ,
					m.mState, 
					m.mIsFtp,
					m.mEditFile,
					m.mDeleteFile,
					m.mCdnEditFile,
					m.mCdnDeleteFile,
					m.mMsgFile,
					m.mCdnMsgFile,
					m.mDescription
					FROM {$this->table} m
					WHERE m.mId = {$mId} {$where_str} AND m.mIsDelete = 0 
					LIMIT 1";
			
			$manage_rows = $this->db->getOneRs($sql);

			if ( empty($manage_rows)) {
				echo '非法进入!';
				exit;
			}
	
			$site_option = getSiteInfo($manage_rows['sId'], true);//站点下拉框	
			$size_user_option = getSiteUser($manage_rows['sId'], true);//站点用户下拉框	
			
			$GLOBALS['smarty']->assign('site_option', $site_option);
			$GLOBALS['smarty']->assign('size_user_option', $size_user_option);
			$GLOBALS['smarty']->assign('type', $this->type);
			$GLOBALS['smarty']->assign('manage_rows', $manage_rows);
			$GLOBALS['smarty']->assign('form_act', 'edit');
			$GLOBALS['smarty']->assign('form_value', '修改');
			$GLOBALS['smarty']->display('task_manage_edit.htm'); 
			
			
		} else {//增加
			
			$sId = (int) $_GET['sId'];//站点ID
			$IsFtp = (int) $_GET['IsFtp'];//是否ftp上传
			
			$site_option = getSiteInfo($sId, true);//站点下拉框	
			$GLOBALS['smarty']->assign('back_url', $_SERVER['HTTP_REFERER']);
			$GLOBALS['smarty']->assign('site_option', $site_option);
			$GLOBALS['smarty']->assign('type', $this->type);
			$GLOBALS['smarty']->assign('IsFtp', $IsFtp);
			$GLOBALS['smarty']->assign('form_act', 'add');
			$GLOBALS['smarty']->assign('form_value', '增加');
			$GLOBALS['smarty']->display('task_manage_add.htm'); 
		}
	}
	
	/**
	* 显示文件路径
	* @param   array      	$data
	* @return  string
	*/
	public function showFileList() {
		$file_name = trim($_GET['file_name']);//获取文件路径
		if ( !is_file($file_name) ) {
			echo '不是一个文件！';
			exit;
		}
		
		$file_array = file($file_name);
		$data_array = $row = array();

		if ( !empty($_GET['is_cdn']) && empty($_GET['is_msg']) ) {
			foreach ($file_array AS $key => $value) {
				$row['value'] =  $value;
				$row['herf'] = $value;
				$data_array[] = $row;
			}
		} elseif ( empty($_GET['is_cdn']) && empty($_GET['is_msg']) ) {
			foreach ($file_array AS $key => $value) {
				$row['value'] =  $value;
				$row['herf'] = str_replace(DOC_ROOT, DOC_URL, $value);
				$data_array[] = $row;
			}
		} elseif ( empty($_GET['is_cdn']) && !empty($_GET['is_msg']) ) {
			$data_array = $file_array;
		}
		
		$str_result = implode('/', $data_array) ;
		$mID = (int) $_GET['mId'];
		
		if (stripos($_GET['file_name'] , 'pubMsg.txt') &&  !empty($str_result) && stripos($str_result , "同步成功") ){
		
			updateTaskState($mID, 4);
		} else {
//			echo '发布失败' ;
		} 
		
		unset($file_array, $row);
		
		$GLOBALS['smarty']->assign('is_msg', (int) $_GET['is_msg']);
		$GLOBALS['smarty']->assign('file_name', $file_name);
		$GLOBALS['smarty']->assign('file_array', $data_array);
		$GLOBALS['smarty']->assign('back_url', $_SERVER['HTTP_REFERER']);
		$GLOBALS['smarty']->display('task_manage_filelist.htm'); 
	}
	
	/**
	* 提交操作
	* @param   array      	$data
	* @return  string
	*/
	public function editSubmit() {
		
		//验证数据合法性
		if ( empty($_POST['Name']) ) {
			
			echo '任务名称不能为空！';
			exit;
		}
		
		if ( !in_array($this->type, array('self', 'admin') ) ) {
			echo "非法进入！";
			exit;
		}
		
		//封装数据
		$mId = (int) $_POST['mId'];
		$data = array(	'mName' => trim($_POST['Name']),
						'mDescription' => trim($_POST['Description']),
					);
		
		//提交表单
		if( $_POST['act'] == 'add' && empty($mId) ) { //增加任务操作
			
			//服务端验证
			$IsFtp = (int) $_POST['IsFtp'];
			$sId = (int) $_POST['sId'];
			$nums = $this->getUserTaskNums($sId, $IsFtp);
			if ($nums > 0 ) {
				echo "你已经有改网站的未完成任务,请先完成! 再来增加该网站新的任务！";
				exit;
			}
			
			$data['mCreatAid'] = $_SESSION['AID'];
			$data['mCreatTime'] = $_SERVER['REQUEST_TIME'];
			$data['mIsFtp'] = $IsFtp;
			$data['sId'] = $sId;
			
			//增加任务
			$update_array = insertTask($data, $IsFtp);
			
			if ( !empty($update_array['mId']) ) {
				$alert_title = '增加成功！';
				$location_url = $_POST['back_url'];
				
			} else {
				$location_url = "/wondershare/task_manage.php?action=editData&type={$this->type}";
				$alert_title = '增加失败！';
			
			}
			
			unset($update_array, $data);
			mainAlert($alert_title, $location_url);
			
		} elseif ( $_POST['act'] == 'edit' && !empty($mId)) {//修改任务操作
			
			if ( !empty($_POST['TestAid']) ) {//任务状态为未测试，用户选择测试人员
				$data['mTestAid'] = (int) ($_POST['TestAid']);
				$data['mState'] = 1;
			}
			
			//返回影响的行数
			$lines = $this->db->update($this->table, $data, " mId = {$mId} AND mIsDelete = 0  ");
			if ( $lines > 0 ) {
				
				$location_url = "/wondershare/task_manage.php?type={$this->type}";
				$alert_title = '修改成功！';
				
			} else {
				$location_url = "/wondershare/task_manage.php?action=editData&mId={$mId}&type={$this->type}";
				$alert_title = '修改失败！';
			
			}
			
			unset($data);
			mainAlert($alert_title, $location_url);
			
		}
		
	}
	
	
	/**
	* Ajax处理
	* @return  array
	*/
	public function ajaxTask() {
		
		
		if ($_GET['action_type'] == 'delete') { //删除任务处理
				
				//以下为验证
				$str_manage_id = trim($_GET['str_manage_id']);
				if (empty($str_manage_id)) {
					echo "任务ID不能为空！";
					exit;
				}
				
				$where_str = " FIND_IN_SET(mId, '{$str_manage_id}') ";
				
				if ($this->type == 'self') {
					$where_str .= " AND mCreatAid = '{$_SESSION['AID']}' ";
				} 
				
				$data = array( 'mIsDelete' => 1 );
				$rows_affected = $this->db->update($this->table, $data, $where_str);	
				$str = $rows_affected >= 1 ? '删除成功' : '删除失败'; 
				echo $str;
				exit;
			
			
		} elseif ($_GET['action_type'] == 'update_state') { //修改任务状态处理
			
			//以下为验证

			$mId = (int) $_GET['mId'];
			if ( empty($mId) ) {
				echo "任务ID不能为空！";
				exit;
			}
			
			$data = array( 'mState' => (int) $_GET['state'] );
			if ($_GET['state'] == 3)  {//修改发布人和时间
				$data['mPubAid'] = $_SESSION['AID'];
				$data['mPubTime'] = $_SERVER['REQUEST_TIME'];
			}
			
			$rows_affected = $this->db->update($this->table, $data, " mId = {$mId}");	
			$str = $rows_affected >= 1 ? '修改成功' : '修改失败'; 
			echo $str;
			exit;
			
		} elseif ($_GET['action_type'] == 'is_exist_site_task' ) { //查看用户是否已经有具体网站的未完成任务
			
			//以下为验证
			$sId = (int) $_GET['sId'];
			$IsFtp = (int) $_GET['IsFtp'];
			if ( empty($sId) ){ //未选择网站
				echo "你未选择任务站点！";
				exit;
			}
			
			$nums = $this->getUserTaskNums($sId, $IsFtp);
			echo $nums > 0 ? 'yes' : 'no';
			exit;
			
		}  elseif ($_GET['action_type'] == 'get_task_file' ) { //得到任务文件路径(cdn, 修改增加，以及修改)
			
			//以下为验证
			$sId = (int) $_GET['sId'];
			$IsFtp = (int) $_GET['IsFtp'];
			if ( empty($sId) ){ //未选择网站
			
				echo json_encode( array('msg' => "你未选择任务站点！") );
				exit;
			}
			
			$file_row =  getUserTaskFileInfo($sId, $IsFtp);//获取任务相应的文件路径
			
			if ( empty($file_row) ) {
				$file_row = insertTask(array(), $IsFtp, 1, $sId);
				
			} elseif ( $file_row['mState'] != 0 ) {
				echo json_encode( array('msg' => "你已经有该站点的任务，但未处理完，请赶快处理完任务吧！", 'is_create' => 0) );
				exit;
			}
			
			$file_row['msg'] = '';
			$file_row['is_create'] = 0;
			echo json_encode($file_row);
			exit;
		}  elseif ($_GET['action_type'] == 'get_task_file' ) { //得到任务文件路径(cdn, 修改增加，以及修改)
			
		}
		
		
	}
	
	/**
	* 查看用户是否已经有具体网站的未完成任务
	* @param   int      	$sId 站点ID
	* @param   int      	$IsFtp 是否是ftp任务
	* @return  int
	*/
	public function getUserTaskNums($sId = 0, $IsFtp = 0) {
		
			$sql = "SELECT COUNT(1) nums 
					FROM task_manage 
					WHERE mCreatAid = '{$_SESSION['AID']}' AND sId = {$sId} AND mState != 4 AND mIsFtp = {$IsFtp} AND mIsDelete = 0";
			return  $this->db->getOne($sql);
	}
	
	/**
	* 得到任务站点用户信息
	* @return  array
	*/
	public function getUserOptionInfo($search_array = array()) {
		
		$field_array = array('mCreatAid', 'mTestAid', 'mPubAid');
		$rows = array();
		foreach ($field_array AS $key => $value) {
			
			$str = '';
			$sql = "SELECT m.{$value}, a.AName
					FROM {$this->table} m
					LEFT JOIN Admin a ON m.{$value} = a.AID
					WHERE m.mIsDelete = 0 AND m.{$value} != 0
					GROUP BY m.{$value} 
					ORDER BY  m.{$value} ASC ";
			$result = $GLOBALS['db']->query($sql);
			
			while ($row = $GLOBALS['db']->fetch_array($result, MYSQL_ASSOC)) {
				
				if ($row["{$value}"] == $search_array["{$value}"]) {
					$str .= " <option value='{$row["{$value}"]}' selected='selected'>{$row["AName"]}</option>";
				} else {
					$str .= " <option value='{$row["{$value}"]}'>{$row["AName"]}</option>";
				}
				
				
			}
			$rows["{$value}"] = $str;
		}
		
		return $rows;
		
	}
	
	/**
	* 搜索
	* @param   array        $get     表单提交搜索
	* @return  string
	*/
	public function getSearchParameters($search_array = array()) {
		
		$where_str = '';
		$url_str = "&url_page=1&type={$search_array['type']}";
		
		if ( !empty($search_array['mId']) ) {//搜索ID
			
			$where_str .= " AND m.mId = {$search_array['mId']}" ;
			$url_str .= "&mId={$search_array['mId']}";
		} else {
			
			if( !empty($search_array['mName']) ) {//搜索任务名称
				$where_str .= " AND m.mName LIKE '%{$search_array['mName']}%' ";
				$url_str .= "&mName={$mName}";
			}
			
			if( !empty($search_array['sId']) ) {//搜索任务站点

				$where_str.= " AND m.sId = {$search_array['sId']} ";
				$url_str .= "&sId={$search_array['sId']}";
			}
			
			if( !empty($search_array['mCreatAid']) ) {//搜索任务创建人

				$where_str .= " AND m.mCreatAid = '{$search_array['mCreatAid']}' ";
				$url_str .= "&mCreatAid={$search_array['mCreatAid']}";
			}
			
			if( !empty($search_array['mTestAid']) ) {//搜索测试人
				$where_str .= " AND m.mTestAid = '{$search_array['mTestAid']}' ";
				$url_str .= "&mTestAid={$search_array['mTestAid']}";
			}
			
			if( !empty($search_array['mPubAid']) ) {//搜索任务发布人
				$where_str .= " AND m.mPubAid = '{$search_array['mPubAid']}' ";
				$url_str .= "&mPubAid={$search_array['mPubAid']}";
			}
			
			if ( $search_array['type'] == 'test' ) {
				$where_str .= " AND m.mState = 1 ";
			} elseif ($search_array['type'] == 'pub' ) {
				$where_str .= " AND m.mState = 3   ";
			}
		}
		
		return array('where_str' => $where_str, 'url_str' => $url_str);
		
	}


}


$action    = $_REQUEST['action']; 

$task_manage   = new TaskManage;
if ( method_exists($task_manage, $action) )  {
	$task_manage->$action();
} else {
	$task_manage->index();
}

?>
